import store from '../store/index'

export default {
    install(Vue, options) {
        var configObject = {
                cookiesSetting: {
                    name: "XVueProjectAMS",
                }
            }
            // 添加配置信息对象
        Vue.prototype.$appRuntime = configObject;

        /**
     * 权限检查方法
     * @param menuCode 菜单编码
     * @param resourceCode 资源编码
     * @returns {boolean} true：有权限，false: 无权限
     */
    Vue.prototype.$_has = function (menuCode, resourceCode, el) {
        console.log('$_has==>', menuCode, resourceCode);
        if (!menuCode || !resourceCode) {
          return false;
        }
        let resourceInfo = store.getters.getResourceList(menuCode);
        console.log('resourceInfo==>', resourceInfo);
        // let resourceInfoStr = {'resourceInfo':[{'resourceCode':'phCpOnQuery','resourceId':121,'permission':false},{'resourceCode':'phCpOnExport','resourceId':122,'permission':true}]};
        if (!resourceInfo) {
          return false;
        }
        let flag = false;
        for (let i = 0; i < resourceInfo.length; i++) {
          if (resourceInfo[i].resourceCode === resourceCode && resourceInfo[i].permission === 'read') {
            flag = true;
          }
        }
        return flag;
      };
  
      /**
       * 注册一个全局自定义指令 `v-permission`
       * 例: <el-button v-permission='{menuCode:'phtest', resourceCode: 'btnCode'}' />
       */
      Vue.directive('permission', {
        // 当被绑定的元素插入到 DOM 中时……
        inserted (el, binding, vnode) {
          const {value} = binding;
          if (!value || !Vue.prototype.$_has(value.menuCode, value.resourceCode, el)) {
            el.parentNode.removeChild(el);
          }
        }
      });

        // 登录 
        // loginForm 登录的参数 object
        // callBack 回调函数 function
        Vue.prototype.logo = function(loginForm, callBack) {
            Vue.prototype.axios.post('/api/dataServer/UserLogin', loginForm)
                .then(function(res) {
                    console.log(res);
                    if (res.data.isSuccess == "Y") {
                        Vue.prototype.$cookies.set(configObject.cookiesSetting.name,
                            res.data.data);
                        //callBack.call(Vue, true, res.data.data);
                    } else {
                        callBack.call(Vue, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    callBack.call(Vue, false, "serverError");
                });

        };
        /**
         * 将查询对象转换为数组
         * @param formQueryCondition
         * @returns {Array}
         */
        function queryObjToArray (formQueryCondition) {
            if (!formQueryCondition) {
            return formQueryCondition;
            }
            let resultArr = [];
            Object.keys(formQueryCondition).forEach(function (item) {
            // formQueryCondition[item].key = item;
            // formQueryCondition[item].group = item;
            resultArr.push(formQueryCondition[item]);
            });
            return resultArr;
        };
        Vue.prototype.queryObjToArray = function(formQueryCondition) {
            if (!formQueryCondition) {
            return formQueryCondition;
            }
            let resultArr = [];
            Object.keys(formQueryCondition).forEach(function (item) {
            // formQueryCondition[item].key = item;
            // formQueryCondition[item].group = item;
            resultArr.push(formQueryCondition[item]);
            });
            return resultArr;
        };
        // 执行通用查询
        Vue.prototype.queryModel = function(className, opKey, formQueryCondition, pager, sort, callback) {
            var queryRequest = {
                className: className,
                opKey: opKey,
                params: queryObjToArray(formQueryCondition),
                pageSize: pager.curSize,
                pageNum: pager.curPage,
                sort:[{col:sort.key,order:sort.dir}],
                userInfo: Vue.prototype.$cookies.get(configObject.cookiesSetting.name)
            };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              }
            this.axios.post('/api/querypage', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    // alert(JSON.stringify(res));
                    // alert(res.data.code);
                    if (res.data.code == "SUCCESS") {
                        callback.call(Vue, true, res.data.data);
                    } else {
                        callback.call(Vue, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    callBack.call(Vue, false, "serverError");
                });
        };

        //查询用户菜单按钮权限
        Vue.prototype.readUserResource = function(viewModel,menuCode, callback) {
            var queryRequest = {
                className: "com.ispr.iptv.entity.sys.ViewUserMenuResource",
                opKey: "Query",
                params: [{key: 'menuCode',op: '=',val: menuCode}],
                userInfo: Vue.prototype.$cookies.get(configObject.cookiesSetting.name)
            };
            let headersObj = {
                'Content-Type': 'application/json',
                'App-Type': this.getUserInfo().appType,
                'Language': this.getUserInfo().language,
                'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
                'X-AOHO-UserId': this.getUserInfo().keyID
              };
            this.axios.post('/api/getResource', queryRequest, { headers: headersObj })
                .then(function(res) {
                    // alert(JSON.stringify(res));
                    // alert(res.data.code);
                    if (res.data.code == "SUCCESS") {
                        var resourceInfoTemp = viewModel.$store.getters.getAllResourceList;
                        //alert(JSON.stringify(res.data.data));
                        resourceInfoTemp.set(menuCode, res.data.data);
                        console.log('resourceInfoTemp==>', resourceInfoTemp);
                        viewModel.$store.commit('setResourceInfo', resourceInfoTemp);
                        callback.call(Vue, true, menuCode);
                    } else {
                        callback.call(Vue, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    callback.call(Vue, false, "serverError");
                });
        };

        /**
     * 根据菜单编码查询资源信息
     * @param viewModel vue对象
     * @param menuCode 菜单编码
     * @returns {Promise<any>}
     */
    // Vue.prototype.readUserResource123 = function (viewModel, menuCode) {
    //     try {
    //         var queryRequest = {
    //             className: "com.ispr.iptv.entity.sys.ViewUserMenuResource",
    //             opKey: "Query",
    //             params: [{key: 'menuCode',op: '=',val: menuCode}],
    //             userInfo: Vue.prototype.$cookies.get(configObject.cookiesSetting.name)
    //         };
    //         let webSeturl = '/api/getResource';
    //         let postData = JSON.stringify(queryRequest);
    //         return new Promise((resolve, reject) => {
    //         fetch({
    //           method: 'post',
    //           url: webSeturl,
    //           data: postData
    //         }).then((response) => {
    //           console.log('读取用户的菜单资源返回结果==>', response);
    //           let json = response.data;
    //           if (json.code === 'SUCCESS') {
    //             let resourceInfoTemp = viewModel.$store.getters.getAllResourceList;
    //             resourceInfoTemp.set(menuCode, json.data);
    //             console.log('resourceInfoTemp==>', resourceInfoTemp);
    //             viewModel.$store.commit('setResourceInfo', resourceInfoTemp);
    //           } else {
    //             viewModel.$message({
    //               message: json.msg,
    //               type: 'warning'
    //             });
    //           }
    //           resolve(response.data);
    //         }).catch((error) => {
    //           console.log(error);
    //           viewModel.$message({
    //             dangerouslyUseHTMLString: true,
    //             message: '访问错误<br>异常代码: ' + error.request.status + '<br/>异常消息: ' + error.request.responseText,
    //             type: 'error'
    //           });
    //           reject(error);
    //         });
    //       });
    //       // return
    //     } catch (e) {
    //       console.log('读取用户的菜单资源', e);
    //       alert(e);
    //     }
    //   };

        // 执行命令
        Vue.prototype.procCommand = function(commandCode, className, commandArgs, commandBody,editFormCheck,
            callback) {
            var requestArgs = {
                commandCode: commandCode,
                className: className,
                commandArgs: commandArgs,
                commandBody: commandBody,
                params: editFormCheck,
                userInfo: Vue.prototype.$cookies.get(configObject.cookiesSetting.name)
            };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              }
            Vue.prototype.axios.post('/api/execute',
                    requestArgs, { headers: this.headersObj })
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        callback.call(Vue, true, res.data.data);
                    } else {
                        callback.call(Vue, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    callback.call(Vue, false, "serverError");
                });
        };

        /**
     * 文件下载
     * @param viewModel
     * @param url 访问的地址
     * @param paramKey 通过文件名下载  用户下载模板
     * @param paramValue 通过任务ID下载  用户导入错误文件下载
     * @param filename 文件名
     */
    Vue.prototype.downloadByIdOrName = function downloadByIdOrName (viewModel, url, paramKey, paramValue, filename) {
        let requestUrl = "/api" + url;
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open('POST', requestUrl, true);
        xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xmlhttp.setRequestHeader('Authorization', 'Bearer ' + Vue.prototype.$cookies.get(configObject.cookiesSetting.name).tokenCode);
        xmlhttp.setRequestHeader('X-AOHO-UserId', Vue.prototype.$cookies.get(configObject.cookiesSetting.name).keyID);
        xmlhttp.setRequestHeader('Accept-Language', Vue.prototype.$cookies.get(configObject.cookiesSetting.name).language);
        if (this.isExistResourceCode(this)) {
            xmlhttp.setRequestHeader('X-AOHO-Resource', this.menuCode + ',' + this.currentResCode);
          }
        xmlhttp.responseType = 'blob';
        xmlhttp.onload = function (e) {
          if (this.status === 200) {
            let blob = this.response;
            if (blob.type === 'application/json') {
              viewModel.$message.warning('导出数据不存在，导出失败！');
              return false;
            }
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, filename);
            } else {
              let a = document.createElement('a');
              let url = (window.URL) ? window.URL.createObjectURL(blob) : window.webkitURL.createObjectURL(blob);
              a.href = url;
              a.download = filename;
              document.body.appendChild(a);
              a.click();
              window.URL.revokeObjectURL(url);
            }
          }
        };
        xmlhttp.send(paramKey + '=' + paramValue);
      };
    // Vue.prototype.downloadByIdOrName1 = function downloadByIdOrName1 (viewModel, url, paramKey, paramValue, filename) {
    //     var fd = new FormData()
    //     fd.append(paramKey, paramValue)
    //   var reqData = {
    //     userInfo: Vue.prototype.$cookies.get(configObject.cookiesSetting.name)
    //   }
    //   let config = {
    //     headers: {
    //         'Content-Type': 'application/json'
    //     }
    // }
    //   this.axios.post(url, fd, config, {
    //     responseType: 'blob'
    //   }).then(res => {
    //     let blob = res.data
    //     let reader = new FileReader()
    //     reader.readAsDataURL(blob)
    //     reader.onload = (e) => {
    //       let a = document.createElement('a')
    //       a.download = filename
    //       a.href = e.target.result
    //       document.body.appendChild(a)
    //       a.click()
    //       document.body.removeChild(a)
    //     }
    //   });
    // };
        //根据数据表ID查询数据
        Vue.prototype.queryModelByKeyID = function(className, keyID, queryArgs, callback) {
            var queryRequestArgs = {
                className: className,
                keyID: keyID,
                opKey: queryArgs,
                userInfo: Vue.prototype.$cookies.get(configObject.cookiesSetting.name)
            };
            Vue.prototype.axios.post('/api/QueryDomainModelByKeyID', queryRequestArgs, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        callback.call(Vue, true, res.data.data);
                    } else {
                        callback.call(Vue, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    callBack.call(Vue, false, "serverError");
                });
        };

        //根据字典类型编号获取字典中的基础数据
        Vue.prototype.findByTypeCode = function(valueTypeCode, callback) {
            var queryRequest = {
                className: "com.ispr.iptv.entity.sys.SysValue",
                opKey: "Value",
                params: [{"val":valueTypeCode},{"val":"Available"}],
                userInfo: Vue.prototype.$cookies.get(configObject.cookiesSetting.name)
            };
            this.axios.post('/api/findByTypeCode', queryRequest, {headers: this.headersObj})
            .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        callback.call(Vue, true, res.data);
                    } else {
                        callback.call(Vue, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    callBack.call(Vue, false, "serverError");
                });
        };
        
        // 检查是否登录 获得用户对象
        Vue.prototype.getUserInfo = function() {
            //console.log(Vue.prototype.$cookies.isKey(configObject.cookiesSetting.name));
            if (Vue.prototype.$cookies.isKey(configObject.cookiesSetting.name)) {
                var userInfo = Vue.prototype.$cookies.get(configObject.cookiesSetting.name);
                return userInfo;
            } else {
                window.location.href = "login.html";
            }
        };

        //资产审核和资产审核确认页面的特殊查询
        Vue.prototype.auditConfirmQuery = function(url,className, opKey, formQueryCondition, pager, sort, callback){
            var queryRequest = {
                className: className,
                opKey: opKey,
                params: queryObjToArray(formQueryCondition),
                pageSize: pager.curSize,
                pageNum: pager.curPage,
                sort:[{col:sort.key,order:sort.dir}],
                userInfo: Vue.prototype.$cookies.get(configObject.cookiesSetting.name)
            };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              }
            this.axios.post(url, queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    // alert(JSON.stringify(res));
                    // alert(res.data.code);
                    if (res.data.code == "SUCCESS") {
                        callback.call(Vue, true, res.data.data);
                    } else {
                        callback.call(Vue, false, res.data);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    callBack.call(Vue, false, "serverError");
                });
        },

        /**
         * 通过时间戳返回yyyy-MM-dd HH:mm:ss
         * @param timestamp
         * @returns {string}
         */
        Vue.prototype.formatDate = function(param) {
            var time = new Date(param);
            var y = time.getFullYear();
            var m = time.getMonth()+1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
        };

        /**
     * 判断资源编码和菜单编码是否存在 存在则返回true
     * @param viewModel
     * @returns {boolean}
     */
    Vue.prototype.isExistResourceCode = function isExistResourceCode (viewModel) {
        // alert(viewModel.menuCode);
        // alert(viewModel.currentResCode);
        return (viewModel && viewModel.menuCode && viewModel.currentResCode && viewModel.menuCode !== '' && viewModel.currentResCode !== '');
      };
        
        function add0(m){
            return m<10?'0'+m:m;
        };


        
    },
}